package com.zlj.jdbc.bignumber.map3;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.rowset.serial.SerialBlob;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import com.zlj.jdbc.demo.JdbcUtils;

/**
 * 大数据 
 * 把Map3保存到数据库中，并从数据库中取出mp3
 * 
 * @author bashen
 *
 */
public class Map3Demo {

	/**
	 * 把mp3保存到数据库中
	 */
	@Test
	public void test01() {
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "insert into tab_bin values(?,?,?)";
			statement = conn.prepareStatement(sql);
			statement.setInt(1, 1);
			statement.setString(2, "music.mp3");
			/*
			 * 需要得到blob
			 * 1、有文件，目标是变为Blob
			 * 2、先把文件变为byte[]
			 * 3、再使用byte[]创建Blob 
			 */
			byte[] array = IOUtils.toByteArray(new FileInputStream("D:/music.mp3"));
			Blob blob = new SerialBlob(array);  
			statement.setBlob(3, blob);
			/*
			 * 当执行下面语句时可能会抛异常，此时需要在mysql的my.ini文件中加入下面这句：
			 * max_allowed_packet = 10485760
			 */
			statement.executeUpdate();
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(conn != null) conn.close();
				if(statement != null) statement.close();
			} catch(Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	/*
	 * 从数据库中取出mp3
	 */
	@Test
	public void test02() {
		Connection conn = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "select * from tab_bin ";
			statement = conn.prepareStatement(sql);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				Blob blob = resultSet.getBlob("data");
				//把Blob变成硬盘上的文件
				/*
				 * 1、通过Blob的到输入流对象
				 * 2、自己创建输出流对象
				 * 3、把输入流中的数据写入输出流中
				 */
				InputStream in = blob.getBinaryStream();
				OutputStream out = new FileOutputStream("D:/workspace/jdbc/jdbcDemo/music.mp3");
				IOUtils.copy(in, out);
			}
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(conn != null) conn.close();
				if(statement != null) statement.close();
			} catch(Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
}
